import { defineComponent, Component, ref, h, computed } from 'vue'
import { NIcon, NLayoutSider, NMenu, NScrollbar } from 'naive-ui'
import type { MenuOption } from 'naive-ui'
import styles from './index.module.scss'
import * as vicon from '@vicons/ionicons5'
import { useMenu } from './use-menu'
import { Menu } from '@/service/modules/menu/types'
import TabsUtils from '@/store/tabs/tabs-util'
import { useRouter } from 'vue-router'

function renderIcon(iconName: string) {
  const icon = vicon[iconName]
  return () => h(NIcon, null, { default: () => h(icon) })
}

const SiderBar = defineComponent({
  name: 'SiderBar',
  setup() {
    //获取用户菜单
    const { variables, getUserMenus } = useMenu()
    const collapsed = ref(true)
    getUserMenus()
    const menuOptions = computed((): MenuOption[] => {
      const menus: MenuOption[] = []
      variables.userMenus.forEach((item: Menu) => {
        menus.push({
          label: item.name,
          key: item.id,
          tabName: item.tabName,
          icon: renderIcon(item.icon),
          disabled: item.disabled,
          children: createChildMenu(item)
        })
      })
      return menus
    })
    //递归获取菜单树
    const createChildMenu = (menu: Menu): MenuOption[] | undefined => {
      if (menu.type === 1) return undefined
      const childs: MenuOption[] = []
      if (!menu.subMenus) return childs
      menu.subMenus.forEach((item: Menu) => {
        childs.push({
          label: item.name,
          key: item.id,
          tabName: item.tabName,
          icon: renderIcon(item.icon),
          disabled: item.disabled,
          children: createChildMenu(item)
        })
      })
      return childs
    }
    const inverted = ref(true)
    const router = useRouter()
    const handleSelected = (key: string, item: MenuOption) => {
      router.push({
        path: `/${item.tabName}`,
        query: {
          tab: item.label as string,
          tabName: item.tabName as string
        }
      })
    }
    return {
      inverted,
      collapsed,
      handleSelected,
      menuOptions
    }
  },
  render() {
    return (
      <div class={styles.container}>
        <NLayoutSider
          bordered
          collapse-mode='width'
          collapsed-width={50}
          width='240'
          inverted={this.inverted}
          collapsed={this.collapsed}
          onCollapse={() => {
            this.collapsed = true
          }}
          onExpand={() => {
            this.collapsed = false
          }}
          show-trigger
        >
          <NScrollbar style='max-height: 100%' trigger='none'>
            <NMenu
              inverted={this.inverted}
              indent={25}
              collapsed-width={50}
              collapsed-icon-size={22}
              options={this.menuOptions}
              onUpdateValue={this.handleSelected}
              collapsed={this.collapsed}
            />
          </NScrollbar>
        </NLayoutSider>
      </div>
    )
  }
})
export default SiderBar
